<?php

namespace app\adminapi\controller;

use app\model\PostModel;
use app\model\UsersModel;
use app\model\TopicModel;
use Webman\Http\Request;

class Post extends BaseAdminApi
{
    protected ?string $dataModel = PostModel::class;
    protected array $with = ['user', 'topic'];
    protected array $allowSearch = ['title', 'content', 'status', 'user_id', 'topic_id'];

    /**
     * 获取帖子详情
     */
    public function getPostDetail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return $this->fail('帖子ID不能为空');
        }

        $post = PostModel::with(['user:id,nickname,avatar', 'topic:id,name'])
            ->find($id);

        if (!$post) {
            return $this->fail('帖子不存在');
        }

        return $this->success($post, '获取成功');
    }

    /**
     * 删除帖子
     */
    public function deletePost(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->fail('帖子ID不能为空');
        }

        $post = PostModel::find($id);
        if (!$post) {
            return $this->fail('帖子不存在');
        }

        try {
            // 删除帖子时，需要更新圈子的帖子数量
            $topic = TopicModel::find($post->topic_id);
            if ($topic && $topic->post_num > 0) {
                $topic->decrement('post_num');
            }

            $post->delete();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除帖子
     */
    public function batchDeletePosts(Request $request)
    {
        $ids = $request->post('ids');
        if (empty($ids) || !is_array($ids)) {
            return $this->fail('请选择要删除的帖子');
        }

        try {
            $posts = PostModel::whereIn('id', $ids)->get();
            
            // 统计每个圈子需要减少的帖子数量
            $topicPostCounts = [];
            foreach ($posts as $post) {
                if (!isset($topicPostCounts[$post->topic_id])) {
                    $topicPostCounts[$post->topic_id] = 0;
                }
                $topicPostCounts[$post->topic_id]++;
            }

            // 删除帖子
            PostModel::whereIn('id', $ids)->delete();

            // 更新圈子帖子数量
            foreach ($topicPostCounts as $topicId => $count) {
                $topic = TopicModel::find($topicId);
                if ($topic) {
                    $topic->decrement('post_num', $count);
                }
            }

            return $this->success('批量删除成功');
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }
}